<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="第几天" prop="dayNumber">
        <el-input
          v-model="queryParams.dayNumber"
          placeholder="请输入第几天"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品" prop="productId">
        <el-select
            v-model="queryParams.productId"
            placeholder="请选择旅游产品"
            clearable style="width: 200px;">
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"  
              :value="item.value"
            />
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['travel:itinerary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:itinerary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:itinerary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['travel:itinerary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itineraryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="第几天" align="center" prop="dayNumber">
        <template #default="scope">
          <span>第{{ scope.row.dayNumber}}天</span>
        </template>
      </el-table-column>
      <el-table-column label="产品ID" align="center" prop="productId" />
      <el-table-column label="当日行程标题" align="center" prop="title" />
      <el-table-column label="当日行程描述" align="center" prop="description" />
      <el-table-column label="餐饮安排" align="center" prop="meals" />
      <el-table-column label="住宿安排" align="center" prop="accommodation" />
      <el-table-column label="交通安排" align="center" prop="transportation" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['travel:itinerary:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['travel:itinerary:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品行程对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="itineraryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="form.productId"
            placeholder="请选择旅游产品" @change="handleProductTypeChange"
            clearable
            style="width: 100%">
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"  
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="景点" prop="attractionId">
          <el-select
            v-model="selectedAttractionIds"
            placeholder="请选择景点" multiple
            clearable
            style="width: 100%">
            <el-option
              v-for="item in attractionOptions"
              :key="item.value"
              :label="item.label"  
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="第几天" prop="dayNumber">
          <el-input v-model="form.dayNumber" placeholder="请输入第几天" />
        </el-form-item>
        <el-form-item label="当日行程标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入当日行程标题" />
        </el-form-item>
        <el-form-item label="当日行程描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="餐饮安排" prop="meals">
          <el-input v-model="form.meals" placeholder="请输入餐饮安排" />
        </el-form-item>
        <el-form-item label="住宿安排" prop="accommodation">
          <el-input v-model="form.accommodation" placeholder="请输入住宿安排" />
        </el-form-item>
        <el-form-item label="交通安排" prop="transportation">
          <el-input v-model="form.transportation" placeholder="请输入交通安排" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Itinerary">
import { listItinerary, getItinerary, delItinerary, addItinerary, updateItinerary } from "@/api/travel/itinerary"
import { listByUserid} from "@/api/travel/product"
import { getAttractions,getAttractionsByItineraryId} from "@/api/travel/attraction"
const { proxy } = getCurrentInstance()

const itineraryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const productOptions = ref([])
const attractionOptions = ref([])
const selectedAttractionIds = ref([])

const data = reactive({
  form: {
    productId :0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    dayNumber: null,
    title: null,
    description: null,
    meals: null,
    accommodation: null,
    transportation: null,
  },
  rules: {
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    dayNumber: [
      { required: true, message: "第几天不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "当日行程标题不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询产品行程列表 */
function getList() {
  loading.value = true
  listItinerary(queryParams.value).then(response => {
    itineraryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    itineraryId: null,
    productId: null,
    dayNumber: null,
    title: null,
    description: null,
    meals: null,
    accommodation: null,
    transportation: null,
    createTime: null,
    updateTime: null
  }
  selectedAttractionIds.value=[];
  proxy.resetForm("itineraryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itineraryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加产品行程"
}

const fetchProductData = async () => {
  try {
    const res = await listByUserid();
    if (res.code === 200) { 
      productOptions.value = res.rows.map(item => ({
        value: item.productId,
        label: item.productName
      }));
    } else {
      console.error('获取失败：', res.msg);
    }
  } catch (err) {
    console.error('获取异常：', err);
  }
}

function handleProductTypeChange(productId) {
  getAttractions(productId).then(res => {
    if (res.code === 200) {
      attractionOptions.value = res.rows.map(item => ({
        value: item.attractionId,
        label: item.attractionName
      }));
    }else {
      console.error('获取失败：', res.msg);
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _itineraryId = row.itineraryId || ids.value
  getItinerary(_itineraryId).then(response => {
    form.value = response.data
    getAttractionsByItineraryId(_itineraryId).then(res => {
      if (res.code === 200) {
        selectedAttractionIds.value = res.rows.map(item => item.attractionId) || [];
      }
    })
    handleProductTypeChange(form.value.productId)
    open.value = true
    title.value = "修改产品行程"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["itineraryRef"].validate(valid => {
    if (valid) {
      form.value.attractionIds = selectedAttractionIds.value;
      if (form.value.itineraryId != null) {
        updateItinerary(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addItinerary(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _itineraryIds = row.itineraryId || ids.value
  proxy.$modal.confirm('是否确认删除产品行程编号为"' + _itineraryIds + '"的数据项？').then(function() {
    return delItinerary(_itineraryIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('travel/itinerary/export', {
    ...queryParams.value
  }, `itinerary_${new Date().getTime()}.xlsx`)
}

getList()
fetchProductData()
</script>
